package one.stand.controller;

import cn.hutool.core.util.RandomUtil;
import com.github.pagehelper.PageHelper;
import com.jmp.api.dto.*;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.dto.CardSaveRequest;
import com.jmp.base.dto.CompanyLicenseInfoRequest;
import com.jmp.base.dto.CompanyLicenseInfoResponse;
import com.jmp.feign.CardFeign;
import com.jmp.feign.CompanyFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.dto.CompanyDto;
import one.stand.dto.ConvertUtils;
import one.stand.dto.PageResponse2;
import one.stand.model.ResultModel;
import one.stand.service.CompanyBaseService;
import one.stand.util.AssertUtil;
import one.stand.util.RequestContext;
import one.stand.util.RequestContextHolder;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @author cjr
 */
@Api(description = "店铺")
@RequestMapping("crmApi/supplier")
@RestController
public class SupplierController {
    @Autowired
    private CompanyFeign companyFeign;
    @Autowired
    private CardFeign cardFeign;

    @Autowired
    private CompanyBaseService companyBaseService;

    @ApiOperation("店铺信息")
    @GetMapping("info")
    @SecurityAuthCheck
    public ResultModel<SupplierInfoResponse> info(@RequestAttribute SupplierInfoRequest request) {

        RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        int status;
        String refuseReason = StringUtils.EMPTY;
        if (Objects.isNull(optUser.getCompanyId())) {
            status = 0;
        } else {
            CompanyLicenseInfoRequest licenseInfoRequest = CompanyLicenseInfoRequest.builder().companyId(optUser.getCompanyId()).build();
            ResultModel<CompanyLicenseInfoResponse> licenseInfoResponseResultModel = companyFeign.licenseInfo(licenseInfoRequest);
            AssertUtil.isTrue(licenseInfoResponseResultModel);
            CompanyLicenseInfoResponse licenseInfoResponse = licenseInfoResponseResultModel.getData();
            if (Objects.isNull(licenseInfoResponse.getStatus())) {
                status = 2;
            } else {
                status = licenseInfoResponse.getStatus() + 1;
                refuseReason = licenseInfoResponse.getRefuseReason();
            }
        }

        SupplierInfoResponse response = SupplierInfoResponse.builder()
                .status(status)
                .refuseReason(refuseReason)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("已注册店铺列表（可搜索，分页）")
    @GetMapping("company/select")
    @SecurityAuthCheck
    public ResultModel<SupplierCompanySelectResponse> companySelect(@RequestAttribute SupplierCompanySelectRequest request) {

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<CompanyDto> list = companyBaseService.selectList(request.getKeyword(), null);
        PageResponse2<SupplierCompanySelectResponse.Company> page = ConvertUtils.page2(list, companyDto -> {
            return SupplierCompanySelectResponse.Company.builder()
                    .companyId(companyDto.getCompanyId())
                    .companyName(companyDto.getCompanyName())
                    .build();
        });

        SupplierCompanySelectResponse response = SupplierCompanySelectResponse.builder()
                .companyPage(page)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("保存名片（如创建企业，则同时保存企业）")
    @PostMapping("save")
    @SecurityAuthCheck
    public ResultModel<SupplierSaveResponse> save(@RequestAttribute SupplierSaveRequest request) {
        final RequestContext requestContext = RequestContextHolder.getRequestContext();

        CardSaveRequest cardSaveRequest = CardSaveRequest.builder()
                .companyLogo(request.getCompanyLogo())
                .companyName(request.getCompanyName())
                .licensePhotos(request.getLicensePhotos())
                .password(String.valueOf(RandomUtil.randomInt(100000, 999999)))
//                .companyNotice(request.getCompanyNotice())
//                .industryId(request.getIndustryId())
                .companyId(request.getCompanyId())
                .isClientJxs(BooleanUtils.toBoolean(request.getCompanyType()))

                .logo(request.getLogo())
                .name(request.getName())
                .phone(request.getPhone())
                .personalWx(request.getPersonalWx())
                .email(request.getEmail())
//                .style(request.getStyle())
//                .companyWx(request.getCompanyWx())
//                .photo(request.getPhoto())
//                .position(request.getPosition())
//                .soundRecording(request.getSoundRecording())
//                .soundTime(request.getSoundTime())
//                .briefIntroduction(request.getBriefIntroduction())

                .id(requestContext.getUser().getUserId())
                .companyKey(requestContext.getRequest().getCompanyKey())
                .token(requestContext.getRequest().getToken())
                .build();
        ResultModel resultModel = cardFeign.save(cardSaveRequest);
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }
}
